// pages/2411Ayiliao-pages/patient/add-patient.js
Page({
	data: {
		formData: {
			relationTypeId: null,
			relationTypeName: '',
			name: '',
			idCardTypeId: null,
			idCardTypeName: '',
			idCardNumber: '',
			medicalCardNumber: '',
			phoneNumber: '',
			address: '',
			isDefault: false
		},
		showRelationship: false,
		showIdType: false,
		relationshipOptions: [
			{ id: 1, typeName: '本人', typeCode: 'self' },
			{ id: 2, typeName: '父亲', typeCode: 'father' },
			{ id: 3, typeName: '母亲', typeCode: 'mother' },
			{ id: 4, typeName: '儿子', typeCode: 'son' },
			{ id: 5, typeName: '女儿', typeCode: 'daughter' },
			{ id: 6, typeName: '配偶', typeCode: 'spouse' },
			{ id: 7, typeName: '其他', typeCode: 'other' }
		],
		idTypeOptions: [
			{ id: 1, typeName: '身份证', typeCode: 'idcard' },
			{ id: 2, typeName: '护照', typeCode: 'passport' },
			{ id: 3, typeName: '军官证', typeCode: 'military' },
			{ id: 4, typeName: '港澳通行证', typeCode: 'hongkong' },
			{ id: 5, typeName: '台湾通行证', typeCode: 'taiwan' },
			{ id: 6, typeName: '其他', typeCode: 'other' }
		]
	},

	onLoad(options) {
		console.log('添加就诊人页面加载', options)
		
		// 如果是编辑模式，加载患者信息
		if (options.id) {
			// 查找对应的关系选项
			let relationTypeId = null
			let relationTypeName = ''
			if (options.relationship) {
				const relationOption = this.data.relationshipOptions.find(item => 
					item.typeName === options.relationship || item.typeCode === options.relationship
				)
				if (relationOption) {
					relationTypeId = relationOption.id
					relationTypeName = relationOption.typeName
				}
			}
			
			// 查找对应的证件类型选项
			let idCardTypeId = 1 // 默认身份证
			let idCardTypeName = '身份证'
			if (options.idCardType) {
				const idTypeOption = this.data.idTypeOptions.find(item => 
					item.typeName === options.idCardType || item.typeCode === options.idCardType
				)
				if (idTypeOption) {
					idCardTypeId = idTypeOption.id
					idCardTypeName = idTypeOption.typeName
				}
			}
			
			this.setData({
				formData: {
					relationTypeId: relationTypeId,
					relationTypeName: relationTypeName,
					name: options.name || '',
					idCardTypeId: idCardTypeId,
					idCardTypeName: idCardTypeName,
					idCardNumber: options.idCard || '',
					medicalCardNumber: options.medicalCardNumber || '',
					phoneNumber: options.phone || '',
					address: options.address || '',
					isDefault: options.isDefault === 'true'
				}
			})
		}
		
		this.loadRelationTypes()
		this.loadIdCardTypes()
	},

	// 加载关系类型列表
	async loadRelationTypes() {
		try {
			wx.showLoading({
				title: '加载中...'
			})
			
			wx.request({
				url: 'http://localhost:8080/patient/relationTypes',
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				},
				success: (res) => {
					wx.hideLoading()
					if (res.statusCode === 200 && res.data) {
						let relationData = res.data
						
						// 处理数据格式
						if (typeof relationData === 'string') {
							try {
								relationData = JSON.parse(relationData)
							} catch (e) {
								console.error('JSON解析失败:', e)
								return
							}
						}
						
						if (!Array.isArray(relationData)) {
							if (relationData.data && Array.isArray(relationData.data)) {
								relationData = relationData.data
							} else if (relationData.list && Array.isArray(relationData.list)) {
								relationData = relationData.list
							} else {
								console.error('关系类型数据格式不正确')
								return
							}
						}
						
						// 处理关系类型数据
						const processedData = relationData.map(item => ({
							id: item.id || item.relationTypeId,
							typeName: item.typeName || item.name || item.relationTypeName,
							typeCode: item.typeCode || item.code
						}))
						
						this.setData({
							relationshipOptions: processedData
						})
						
						wx.showToast({
							title: '关系类型加载成功',
							icon: 'success'
						})
					} else {
						console.error('加载关系类型失败:', res.statusCode)
					}
				},
				fail: (error) => {
					wx.hideLoading()
					console.error('网络请求失败:', error)
					wx.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		} catch (error) {
			wx.hideLoading()
			console.error('加载关系类型失败:', error)
		}
	},
	
	// 加载证件类型列表
	async loadIdCardTypes() {
		try {
			wx.showLoading({
				title: '加载中...'
			})
			
			wx.request({
				url: 'http://localhost:8080/patient/idCardTypes',
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				},
				success: (res) => {
					wx.hideLoading()
					if (res.statusCode === 200 && res.data) {
						let idTypeData = res.data
						
						// 处理数据格式
						if (typeof idTypeData === 'string') {
							try {
								idTypeData = JSON.parse(idTypeData)
							} catch (e) {
								console.error('JSON解析失败:', e)
								return
							}
						}
						
						if (!Array.isArray(idTypeData)) {
							if (idTypeData.data && Array.isArray(idTypeData.data)) {
								idTypeData = idTypeData.data
							} else if (idTypeData.list && Array.isArray(idTypeData.list)) {
								idTypeData = idTypeData.list
							} else {
								console.error('证件类型数据格式不正确')
								return
							}
						}
						
						// 处理证件类型数据
						const processedData = idTypeData.map(item => ({
							id: item.id || item.idCardTypeId,
							typeName: item.typeName || item.name || item.idCardTypeName,
							typeCode: item.typeCode || item.code
						}))
						
						this.setData({
							idTypeOptions: processedData
						})
						
						wx.showToast({
							title: '证件类型加载成功',
							icon: 'success'
						})
					} else {
						console.error('加载证件类型失败:', res.statusCode)
					}
				},
				fail: (error) => {
					wx.hideLoading()
					console.error('网络请求失败:', error)
					wx.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		} catch (error) {
			wx.hideLoading()
			console.error('加载证件类型失败:', error)
		}
	},

	// 输入事件处理
	onNameInput(e) {
		this.setData({
			'formData.name': e.detail.value
		})
	},

	onIdCardNumberInput(e) {
		this.setData({
			'formData.idCardNumber': e.detail.value
		})
	},

	onMedicalCardNumberInput(e) {
		this.setData({
			'formData.medicalCardNumber': e.detail.value
		})
	},

	onPhoneNumberInput(e) {
		this.setData({
			'formData.phoneNumber': e.detail.value
		})
	},

	onAddressInput(e) {
		this.setData({
			'formData.address': e.detail.value
		})
	},

	// 关系选择相关方法
	showRelationshipModal() {
		console.log('显示关系选择弹窗')
		this.setData({
			showRelationship: true
		})
	},

	closeRelationshipModal() {
		console.log('关闭关系选择弹窗')
		this.setData({
			showRelationship: false
		})
	},

	selectRelationship(e) {
		const item = e.currentTarget.dataset.item
		console.log('选择关系:', item)
		this.setData({
			'formData.relationTypeId': item.id,
			'formData.relationTypeName': item.typeName,
			showRelationship: false
		})
		console.log('关系选择完成，当前表单数据:', this.data.formData)
	},

	// 证件类型选择相关方法
	showIdTypeModal() {
		console.log('显示证件类型选择弹窗')
		this.setData({
			showIdType: true
		})
	},

	closeIdTypeModal() {
		console.log('关闭证件类型选择弹窗')
		this.setData({
			showIdType: false
		})
	},

	selectIdType(e) {
		const item = e.currentTarget.dataset.item
		console.log('选择证件类型:', item)
		this.setData({
			'formData.idCardTypeId': item.id,
			'formData.idCardTypeName': item.typeName,
			showIdType: false
		})
		console.log('证件类型选择完成，当前表单数据:', this.data.formData)
	},

	// 切换默认就诊人
	toggleDefault(e) {
		this.setData({
			'formData.isDefault': e.detail.value
		})
	},

	// 阻止事件冒泡
	stopPropagation() {
		// 阻止事件冒泡
	},

	// 保存就诊人信息
	async savePatient() {
		console.log('开始保存就诊人，表单数据:', this.data.formData)
		
		// 表单验证
		if (!this.data.formData.relationTypeId) {
			wx.showToast({ title: '请选择关系', icon: 'none' })
			return
		}
		if (!this.data.formData.name || !this.data.formData.name.trim()) {
			wx.showToast({ title: '请输入姓名', icon: 'none' })
			return
		}
		if (!this.data.formData.idCardTypeId) {
			wx.showToast({ title: '请选择证件类型', icon: 'none' })
			return
		}
		if (!this.data.formData.idCardNumber || !this.data.formData.idCardNumber.trim()) {
			wx.showToast({ title: '请输入证件号码', icon: 'none' })
			return
		}
		if (!this.data.formData.phoneNumber || !this.data.formData.phoneNumber.trim()) {
			wx.showToast({ title: '请输入手机号码', icon: 'none' })
			return
		}
		
		try {
			wx.showLoading({
				title: '保存中...'
			})
			
			// 构造请求数据
			const requestData = {
				relationTypeId: this.data.formData.relationTypeId,
				relationTypeName: this.data.formData.relationTypeName,
				name: this.data.formData.name.trim(),
				idCardTypeId: this.data.formData.idCardTypeId,
				idCardTypeName: this.data.formData.idCardTypeName,
				idCardNumber: this.data.formData.idCardNumber.trim(),
				medicalCardNumber: this.data.formData.medicalCardNumber ? this.data.formData.medicalCardNumber.trim() : '',
				phoneNumber: this.data.formData.phoneNumber.trim(),
				address: this.data.formData.address ? this.data.formData.address.trim() : '',
				isDefault: this.data.formData.isDefault ? 1 : 0
			}
			
			console.log('发送到服务器的数据:', requestData)
			
			// 发送到数据库
			wx.request({
				url: 'http://localhost:8080/patient/add',
				method: 'POST',
				header: {
					'Content-Type': 'application/json'
				},
				data: requestData,
				success: (res) => {
					wx.hideLoading()
					console.log('保存响应:', res)
					if (res.statusCode === 200) {
						wx.showToast({ 
							title: '保存成功', 
							icon: 'success'
						})
						
						// 返回上一页并刷新数据
						setTimeout(() => {
							wx.navigateBack()
							// 通知上一页刷新数据
							const pages = getCurrentPages()
							const prevPage = pages[pages.length - 2]
							if (prevPage && prevPage.loadPatientData) {
								prevPage.loadPatientData()
							}
						}, 1500)
					} else {
						wx.showToast({ 
							title: '保存失败', 
							icon: 'none' 
						})
					}
				},
				fail: (error) => {
					console.error('保存就诊人失败:', error)
					wx.hideLoading()
					wx.showToast({ 
						title: '网络请求失败', 
						icon: 'none' 
					})
				}
			})
			
		} catch (error) {
			console.error('保存就诊人失败:', error)
			wx.hideLoading()
			wx.showToast({ 
				title: '网络错误', 
				icon: 'none' 
			})
		}
	}
}) 